'use strict';

const Controller = require('egg').Controller;
const fs = require('fs');
const path = require('path');
const awaitWriteStream = require('await-stream-ready').write;
const sendToWormhole = require('stream-wormhole');
const { streamToBuffer } = require('@jorgeferrero/stream-to-buffer');


class FileController extends Controller {
  async index() {
    const { ctx } = this;
    const res = await ctx.model.Chunk.find({}, { data: 0 })
      .skip(0)
      .limit(Number(100))
      .sort({ createdAt: -1 })
      .exec();
    ctx.body = res;
  }
  async show() {
    const { ctx } = this;
    const { id } = ctx.params;
    const data = await ctx.model.Chunk.findById(id);
    const { filename } = data;
    const encodeName = encodeURI(filename);
    console.log('filename', filename);
    // http 头不能有汉字
    ctx.set('Content-Disposition', `attachment; filename=${encodeName}`);
    ctx.body = data.data;
  }
  async upload() {
    const { ctx, config } = this;
    console.log(ctx.request);
    // 要通过 ctx.getFileStream 便捷的获取到用户上传的文件，需要满足两个条件：
    // 只支持上传一个文件。
    // 上传文件必须在所有其他的 fields 后面，否则在拿到文件流时可能还获取不到 fields。
    const stream = await ctx.getFileStream();
    // 所有表单字段都能通过 `stream.fields` 获取到
    const filename = path.basename(stream.filename); // 文件名称
    const extname = path.extname(stream.filename).toLowerCase(); // 文件扩展名称
    // 组装参数 model
    // const attachment = new this.ctx.model.Attachment();
    // attachment.extname = extname;
    // attachment.filename = filename;
    // attachment.url = `/public/uploads/${attachment._id.toString()}${extname}`;
    // 组装参数 stream
    const target = path.join(
      config.baseDir,
      'app/public/uploads',
      `${Date.now().toString()}${extname}`
    );
    const writeStream = fs.createWriteStream(target);
    // 文件处理，上传到云存储等等
    try {
      await awaitWriteStream(stream.pipe(writeStream));
      const photo = fs.readFileSync(target);
      const res = fs.unlinkSync(target);

      const saveres = await ctx.model.Chunk.create({
        data: photo,
        filename,
        extname,
      });
      console.log('保存结果：', saveres);

      ctx.body = saveres._id;
      ctx.status = 200;
    } catch (err) {
      // 必须将上传的文件流消费掉，要不然浏览器响应会卡死
      await sendToWormhole(stream);
      throw err;
    }

    // ctx.body = 'upload sucess';
    // ctx.status = 200;
  }
}

module.exports = FileController;
